package com.third.customer.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.third.customer.model.dao.CustomerDao;
import com.third.customer.model.dao.CustomerGroupDao;
import com.third.customer.model.dao.param.CustomerGroupParam;
import com.third.customer.model.tables.CustomerGroup;
import com.third.customer.service.CustomerGroupService;
import com.third.customer.service.data.CustomerGroupReq;
import com.third.customer.service.exception.ThirdBadRequestException;
import com.third.customer.service.exception.ThirdNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

/**
 * Created by hehuaichun on 2020/5/23.
 */
@Service
public class CustomerGroupServiceImpl implements CustomerGroupService {

    @Autowired
    private CustomerGroupDao customerGroupDao;

    @Autowired
    private CustomerDao customerDao;

    @Override
    public Page<CustomerGroup> list(CustomerGroupParam param) {
        return customerGroupDao.query(param);
    }

    @Override
    public CustomerGroup getById(Long companyId, Long groupId) {
        return customerGroupDao.getById(companyId, groupId)
                .orElseThrow(() -> new ThirdNotFoundException("客户组不存在!"));
    }

    @Override
    public List<CustomerGroup> getByIds(Long companyId, List<Long> groupIds) {
        return customerGroupDao.getByIds(companyId, groupIds);
    }

    @Override
    public CustomerGroup create(Long companyId, CustomerGroupReq req) {
        Optional<CustomerGroup> optional = customerGroupDao.getByName(companyId, req.getName());
        if (optional.isPresent()) {
            throw new ThirdBadRequestException("录入的客户组信息已经存在!");
        }
        CustomerGroup group = new CustomerGroup();
        group.setCompanyId(companyId);
        group.setName(req.getName());
        group.setDescription(req.getDescription());
        customerGroupDao.insert(group);
        return group;
    }

    @Override
    public CustomerGroup modify(Long companyId, Long groupId, CustomerGroupReq req) {
        getById(companyId, groupId);
        CustomerGroup group = new CustomerGroup();
        group.setId(groupId);
        group.setName(req.getName());
        group.setDescription(req.getDescription());
        customerGroupDao.update(group);
        return group;
    }

    @Override
    public boolean delete(Long companyId, Long groupId) {
        getById(companyId, groupId);
        if (!CollectionUtils.isEmpty(customerDao.getByGroupId(companyId, groupId))) {
            throw new ThirdBadRequestException("当前分组还有客户在使用,不允许删除");
        }
        return customerGroupDao.delete(groupId);
    }
}
